package org.x.chatmod.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.chatmod.dto.ChatFriendDTO;
import org.x.chatmod.dto.ChatFriendResponseDTO;
import org.x.chatmod.entity.ChatFriend;
import org.x.chatmod.entity.ChatUser;
import org.x.chatmod.mapper.ChatFriendMapper;
import org.x.chatmod.mapper.ChatUserMapper;
import org.x.chatmod.service.ChatFriendService;
import org.x.chatmod.vo.FriendVO;
import org.x.commonmod.config.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ChatFriendServiceImpl  extends ServiceImpl<ChatFriendMapper, ChatFriend> implements ChatFriendService {

    @Autowired
    ChatUserMapper chatUserMapper;

    @Autowired
    ChatFriendMapper chatFriendMapper;

    @Override
    public List<FriendVO> getFriendList(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("requester_id", userId);
        queryWrapper.or(" receiver_id="+userId);

        List<ChatFriend> list = this.list(queryWrapper);

        if (list.isEmpty()) {
            return List.of();
        }

        //提取出ChatFriend中的 requesterId 和 receiverId 并去重
        Set<Long> friendIds = list.stream().map(ChatFriend::getRequesterId).collect(Collectors.toSet());
        friendIds.addAll(list.stream().map(ChatFriend::getReceiverId).collect(Collectors.toSet()));
        //去掉自己，这样拿到的就是 好友的id 列表
        friendIds.remove(userId);

        //根据好友的ID，去查询好友的信息
        List<ChatUser> chatUsers = chatUserMapper.selectListByIds(friendIds);
        //
        Map<Long, ChatUser> userMap = chatUsers.stream().collect(Collectors.toMap(ChatUser::getUserId, chatUser -> chatUser));
        //数据转换
        List<FriendVO> friendVOS = list.stream().map(chatFriend -> {
            FriendVO friendVO = new FriendVO();
            friendVO.setFriendId(chatFriend.getRequesterId().equals(userId) ? chatFriend.getReceiverId() : chatFriend.getRequesterId());
            friendVO.setNickname(userMap.get(friendVO.getFriendId()).getUsername());
            friendVO.setAvatar(userMap.get(friendVO.getFriendId()).getAvatar());
            friendVO.setRelationId(chatFriend.getRelationId());
            friendVO.setReceiverId(chatFriend.getReceiverId());
            //状态：0-待确认, 1-已同意, 2-已拒绝, 3-已拉黑
            friendVO.setStatus(chatFriend.getStatus());
            friendVO.setRemark(chatFriend.getRemark());
            friendVO.setLastActive(userMap.get(friendVO.getFriendId()).getLastActive());
            return friendVO;
        }).collect(Collectors.toList());

        return friendVOS;
    }
    @Override
    public ChatUser getFriendInfo(Long userId) {
        //除了密码，返回其他所有信息
        ChatUser chatUser = chatUserMapper.selectOneById(userId);
        chatUser.setPassword(null);
        return chatUser;
    }
    @Override
    public ChatUser updateUserOnlineStatusByLogin(Long userId) {
        // 1. 根据用户ID查询用户信息
        ChatUser chatUser = chatUserMapper.selectOneById(userId);
        if (chatUser == null) {
            return null;
        }

        // 2. 使用 Sa-Token 检查用户登录状态
        if (!StpUtil.isLogin(userId)) {
            chatUser.setStatus(0);
            System.out.println("用户未登录");
        } else {
            chatUser.setStatus(1);
            chatUser.setLastActive(java.time.LocalDateTime.now());
            System.out.println("用户已登录");
        }

        // 3. 更新用户状态并返回
        chatUserMapper.update(chatUser);
        return chatUser;
    }

    /**
     * 发送好友请求
     */
    @Override
    public Long FriendRequest(ChatFriendDTO chatFriendDTO) {
        // 检查是否已存在好友请求（双向检查）
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where("(requester_id = ? and receiver_id = ?)",
                        chatFriendDTO.getRequesterId(), chatFriendDTO.getReceiverId())
                .or("(requester_id = ? and receiver_id = ?)",
                        chatFriendDTO.getReceiverId(), chatFriendDTO.getRequesterId());

        ChatFriend existingRequest = this.getOne(queryWrapper);
        if(existingRequest != null) {
            return existingRequest.getRelationId();
        }

        // 创建新的好友请求
        ChatFriend chatFriend = new ChatFriend();
        BeanUtils.copyProperties(chatFriendDTO, chatFriend);
        chatFriend.setStatus(0);
        chatFriend.setUpdatedAt(java.time.LocalDateTime.now());
        chatFriend.setCreatedAt(java.time.LocalDateTime.now());
        this.save(chatFriend);

        return chatFriend.getRelationId();
    }

    /**
     * 响应好友请求
     */

    @Override
    public String response(ChatFriendResponseDTO chatFriendResponseDTO) {
        ChatFriend chatFriend = new ChatFriend();
        BeanUtils.copyProperties(chatFriendResponseDTO, chatFriend);
        chatFriend.setStatus(chatFriendResponseDTO.getStatus()) ;
        chatFriend.setUpdatedAt(java.time.LocalDateTime.now());
        return this.updateById(chatFriend) ? "响应成功" : "响应失败";

    }

    @Override
    public Result deleteFriend(long relationId) {
        // 1. 检查好友关系是否存在
        ChatFriend chatFriend = chatFriendMapper.selectOneById(relationId);
        if (chatFriend == null) {
            return Result.fail("400","好友关系不存在");
        }

        // 2. 删除好友关系
        boolean isDeleted = chatFriendMapper.deleteById(relationId) > 0;
        if (!isDeleted) {
            return Result.fail("400","删除好友失败");
        }

        // 3. 返回成功结果
        return Result.ok("删除好友成功");
    }

}
